<?
## store question and answer in user session
function writeQA($a, $b, $answer) {	
	$_SESSION['a'] = $a;
	$_SESSION['b'] = $b;
	$_SESSION['answer'] = $answer;
}

## checks the answer from user input
function checkAnswer($userInput) {
			
	$userInput = strip_tags($userInput);
	$userInput = trim($userInput);	
	$userInput = strtolower($userInput);
	
	$answerTextCorrect = numToString( $_SESSION['answer'] );
	
	if ($userInput == $answerTextCorrect) {
		return true;
	} else {
		return false;
	}
	
}

## creates the captcha math equation and form field
function generateCaptcha() {

	$output = "";
	$a = rand(1,5);
	$b = rand(1,5);
	$answer = $a + $b;	
	writeQA($a, $b, $answer);
		
	$output .= "<p><strong>CAPTCHA anti-spam test</strong><br />";
	$output .= "This feature helps us reduce the amount of SPAM registrations received. Please answer the following simple math equation with the correct number <em>spelled out</em> (e.g. zero):<br /><br />";
	$output .= "<label for=\"captcha\" class=\"labelnoformat\">What is ".numToString($a)." plus ".numToString($b)."?</label>";
	$output .= "<input type=\"text\" size=\"5\" name=\"captcha\" id=\"captcha\" onkeyup=\"checkRegistration(); isNumeric(this.id, 'Please SPELL OUT your answer.')\" style='margin-bottom:0px;' /><br /><br />";
	
	return $output;
}

## function for converting number to string text
function numToString( $num )
{
	switch($num)
	{
		case 1: return 'one';
		case 2: return 'two';
		case 3: return 'three';
		case 4: return 'four';
		case 5: return 'five';
		case 6: return 'six';
		case 7: return 'seven';
		case 8: return 'eight';
		case 9: return 'nine';
		case 10: return 'ten';
	}
}

?>
